package org.jeecg.modules.wmhb.job;

import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.util.DateUtils;
import org.jeecg.modules.wmhb.entity.WmContract;
import org.jeecg.modules.wmhb.entity.WmTask;
import org.jeecg.modules.wmhb.service.IWmContractProductService;
import org.jeecg.modules.wmhb.service.IWmContractService;
import org.jeecg.modules.wmhb.service.IWmProjectService;
import org.jeecg.modules.wmhb.service.IWmTaskService;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ContractProgressJob implements Job {
    @Autowired
    private IWmContractService wmContractService;
    @Autowired
    private IWmContractProductService wmContractProductService;
    @Autowired
    private IWmTaskService wmTaskService;

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info(String.format(" =============ContractProgressJob============ !  时间:" + DateUtils.getTimestamp()));
        List<WmContract> wmContractList = wmContractService.confirmedContractList();
        for(WmContract wmContract: wmContractList) {
            BigDecimal progress = new BigDecimal(0);
            List<String> wmContractIdList = new ArrayList<>();
            wmContractIdList.add(wmContract.getId());
            //所有合同产品及其下面的所有根任务（生产任务为设计起点任务，非生产任务为根任务）
            List<String> wmContractProductList = wmContractProductService.selectNodeAndChildrenByContractIdList(wmContractIdList);
            if(!wmContractProductList.isEmpty()) {
                List<WmTask> wmTaskList = wmTaskService.selectRootTaskByContractProduct(wmContractProductList);
                BigDecimal fenziTotal = new BigDecimal(0);
                BigDecimal fenmuTotal = new BigDecimal(0);
                for(WmTask wmTask: wmTaskList){
                    fenziTotal = fenziTotal.add((new BigDecimal(wmTask.getProgress())).multiply(new BigDecimal(wmTask.getWeight())));
                    fenmuTotal = fenmuTotal.add(new BigDecimal(wmTask.getWeight()));
                }
                progress = fenmuTotal.compareTo(BigDecimal.ZERO) == 0 ? (new BigDecimal(0)) : (fenziTotal.divide(fenmuTotal, RoundingMode.HALF_UP));
            }

            wmContract.setProgress(progress.toString());
            wmContractService.updateById(wmContract);
        }
    }
}
